<template>
  <div>
    <!-- 第一层 查询区域 -->
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item>
        <el-input placeholder="用户名" v-model="searchObj.username"></el-input>
      </el-form-item>
      <el-form-item label="">
        <el-button type="primary" icon="el-icon-search" @click="getUserList()">查询</el-button>
      </el-form-item>
      <el-form-item label="">
        <el-button @click="searchObj.username=''">清空</el-button>
      </el-form-item>
    </el-form>

    <!-- 两个按钮 -->
    <el-button type="primary" @click="addUser">添加</el-button>
    <el-button type="danger" @click="deleteAllUser" :disabled="deleteSelections==''">批量删除</el-button>

    <!-- 表格区域 @selection-change="handleSelectionChange"-->
    <el-table :data="records" ref="multipleTable" tooltip-effect="dark" style="width: 100%;margin-top: 10px ;" border @selection-change="handleSelectionChange" v-loading="listLoading">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column label="序号" width="80" type="index" style="text-align:center"> </el-table-column>
      <el-table-column prop="username" label="用户名" width="120">
      </el-table-column>
      <el-table-column prop="nickName" label="用户昵称" show-overflow-tooltip width="100">
      </el-table-column>
      <el-table-column prop="roleName" label="权限列表" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="gmtCreate" label="创建时间" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="gmtModified" label="更新时间" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="address" label="操作" show-overflow-tooltip>
        <template slot-scope="{row,$index}">
          <el-button type="info" icon="el-icon-info" size="mini" @click="subRole(row)"></el-button>
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="updateUser(row)"></el-button>
          <el-popconfirm confirm-button-text='好的' cancel-button-text='不用了' icon="el-icon-info" icon-color="red" title="这是一段内容确定删除吗？" @onConfirm="deleteUser(row)" style="margin-left:8px">
            <el-button type="danger" icon="el-icon-delete" size="mini" slot="reference"></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 @current-change="getSkuList" @size-change="handlerSizeChange" -->
    <el-pagination style="margin-top:10px" :total="total" :current-page="page" :page-sizes="[3,5,10]" :page-size="3" layout="prev,pager,next,jumper,->,sizes,total" @current-change="getUserList"
      @size-change="handlerSizeChange">
    </el-pagination>

    <!-- 添加用户的对话框 dialog -->
    <el-dialog :title="user.id?'修改用户':'添加用户'" :visible.sync="dialogFormVisible">
      <el-form :model="user" ref="form1" :rules="rules">
        <el-form-item label="用户名" label-width="120px" prop="username">
          <el-input placeholder="请输入用户名" v-model="user.username"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" label-width="120px" prop="nickName">
          <el-input placeholder="请输入用户昵称" v-model="user.nickName"></el-input>
        </el-form-item>
        <el-form-item label=" 用户密码" label-width="120px" prop="password" v-show="!user.id">
          <el-input placeholder="请输入密码" v-model="user.password"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!-- @click="dialogFormVisible = false" @click="dialogFormVisible = false" -->
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateUser('form1')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 设置角色的对话框 -->
    <el-dialog title="收货地址" :visible.sync="dialogFormVisible1">
      <el-form>
        <el-form-item label="用户名" label-width="140px">
          <el-input autocomplete="off" :disabled="true" v-model="username"></el-input>
        </el-form-item>
      </el-form>

      <!-- @change="handleCheckAllChange" -->
      <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
      <div style="margin: 15px 0;"></div>
      <!-- @change="handleCheckedCitiesChange" -->
      <el-checkbox-group v-model="userRoleIds" @change="handleCheckedCitiesChange">
        <el-checkbox v-for="role in allRolesList" :label="role.id" :key="role.id">{{role.roleName}}</el-checkbox>
      </el-checkbox-group>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible1 = false">取 消</el-button>
        <el-button type="primary" @click="handlerRole" :loading="loading">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

export default {
  name: 'User',
  data () {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        setTimeout(() => {
          if (this.user.password !== '') {
            this.$refs.form1.validateField('password');
          }
        }, 50)
        callback();
      }
    };
    return {
      records: [],
      // 每一页展示用户的数量
      limit: 3,
      // 当前的页数
      page: 1,
      // 用户管理的总页数
      total: 0,
      // 添加和修改表单的显示与隐藏
      dialogFormVisible: false,
      // 控制分配角色对话框的显示与隐藏
      dialogFormVisible1: false,
      user: {
        nickName: "",
        password: "",
        username: ""
      },
      // 表单验证规则
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { validator: validatePass, trigger: 'blur' }
        ],
      },
      userId: '',
      username: '',
      assignRoles: [],
      allRolesList: [],
      // 所有选中角色的id
      userRoleIds: [],
      // 是否全选
      checkAll: false,
      isIndeterminate: true,
      deleteSelections: [],
      // 搜索关键字
      searchObj: {
        username: ''
      },
      // 加载状态
      listLoading: false,
      // 是否提交申请中
      loading: false
    }
  },
  mounted () {
    this.getUserList()
  },
  methods: {
    // 获取管理用户分页列表
    async getUserList (page = 1) {
      this.page = page
      const { limit, searchObj } = this
      this.listLoading = true
      let result = await this.$API.user.reqGetUserList(this.page, limit, searchObj)
      this.listLoading = false
      // console.log(result);
      if (result.code == 20000) {
        this.records = result.data.items
        this.total = result.data.total
      }
    },
    // 每页展示的数量发生变化时
    handlerSizeChange (limit) {
      this.limit = limit
      this.getUserList()
    },
    // 添加用户按钮，显示对话框
    addUser () {
      this.dialogFormVisible = true
      // 清空user的数据
      // this.user = { username: '', nickName: '', password: '' }
    },
    // 修改用户按钮 ,显示对话框，获取用户当前数据
    async updateUser (row) {
      let result = await this.$API.user.reqGetUserInfo(row.id)
      console.log(result);
      if (result.code == 20000) {
        this.user = result.data.item
      }
      this.dialogFormVisible = true
    },
    // 点击取消按钮，关闭对话框
    cancel () {
      this.dialogFormVisible = false
      this.user = { username: '', nickName: '', password: '' }
    },
    // 添加或者修改用户 保存按钮
    addOrUpdateUser (form1) {
      this.$refs[form1].validate(async (valid) => {
        if (valid) {
          const { user } = this
          this.loading = true
          if (user.id) {
            let result = await this.$API.user.reqUpdateUser(user)
            if (result.code == 20000) {
              this.$message.success('修改用户成功')
            }
          } else {
            let result1 = await this.$API.user.reqAddUser(user)
            if (result1.code === 20000) {
              this.$message.success('添加用户成功')
            }
          }
          this.loading = false
          this.getUserList(user.id ? this.page : 1)
          this.user = {}
          this.dialogFormVisible = false
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 删除用户管理员的操作
    async deleteUser (row) {
      let result = await this.$API.user.reqDeleteUser(row.id)
      if (result.code == 20000) {
        this.$message.success('删除用户成功')
        this.getUserList(this.page)
      }
    },
    // 点击用户按钮 弹出对话框，发起获取角色数据
    async subRole (row) {
      let result = await this.$API.user.reqGetRoles(row.id)
      if (result.code == 20000) {
        this.assignRoles = result.data.assignRoles
        this.allRolesList = result.data.allRolesList
        this.userRoleIds = this.assignRoles.map(item => item.id)
      }
      this.userId = row.id
      this.username = row.username
      this.checkAll = this.allRolesList.length === this.assignRoles.length
      this.isIndeterminate = this.assignRoles.length > 0 && this.assignRoles.length < this.allRolesList.length
      this.dialogFormVisible1 = true
    },
    // 全选按钮
    handleCheckAllChange (value) {
      this.userRoleIds = value ? this.allRolesList.map(item => item.id) : []
      this.isIndeterminate = false;
    },
    // 监听多选框状态的变化
    handleCheckedCitiesChange (value) {
      // console.log(value);
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.allRolesList.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.allRolesList.length;
    },
    // 点击确定按钮，为用户分配角色
    async handlerRole () {
      const userId = this.userId
      const roleIds = this.userRoleIds.join(',')
      let result = await this.$API.user.reqDoAssign(userId, roleIds)
      if (result.code == 20000) {
        this.$message.success('分配角色成功')
      }
      this.dialogFormVisible1 = false
      this.getUserList()
    },
    // 点击第一列的复选框， 监听选择项的变化
    handleSelectionChange (val) {
      this.deleteSelections = val.map(item => item.id)
    },
    // 批量删除按钮的回调
    async deleteAllUser () {
      // console.log(this.deleteSelections);
      let isList = this.deleteSelections
      let result = await this.$API.user.reqDeleteAllUser(isList)
      console.log(result);
      if (result.code == 20000) {
        this.$message.success('删除成功')
      }
    }
  },
}
</script>

<style>
</style>